#include "Common.hpp"

class Init
{
public:
    Init()
    {
        bool r = MakeFifo();
        if (!r)
            return;
        key_t key = GetKey();
        shmid = CreatShm(key);
        std::cout << "shmid:" << shmid << "\n";
        // sleep(5);
        std::cout << "开始将shm映射到进程地址空间\n";
        s = (char *)shmat(shmid, nullptr, 0);
        fd = open(filename.c_str(), O_RDONLY);
    }
    ~Init()
    {
        close(fd);
        std::cout << "将shm从进程地址空间移除\n";
        shmdt(s);

        std::cout << "将共享内存从操作系统中释放\n";
        shmctl(shmid, IPC_RMID, nullptr);
        unlink(filename.c_str());
    }
    int FileDirection()
    {
        return fd;
    }
    const char *ShnPtr()
    {
        return s;
    }

private:
    int shmid;
    int fd;
    char *s;
};

int main()
{
    Init init;
    struct shmid_ds ds;
    std::cout<<std::hex<<ds.shm_perm.__key<<"\n";
    std::cout<<ds.shm_nattch<<"\n";

    while (true)
    {
        int code = 0;
        ssize_t n = read(init.FileDirection(), &code, sizeof(code));
        if (n > 0)
        {
            std::cout << "共享读取：" << init.ShnPtr() << "\n";
        }
        else if (n == 0)
        {
            break;
        }
        else
        {
            std::cerr << "读取错误，错误码：" << errno << "\n";
        }
    }
    return 0;
}